package com.lzy.crm.wechat.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.JsonObject;
import com.lzy.crm.base.util.RedisHelper;
import com.lzy.crm.base.util.StringUtil;
import com.lzy.crm.domain.PpUser;
import com.lzy.crm.service.CreateRoomInfoService;
import com.lzy.crm.service.PpSystemStatusInfoService;
import com.lzy.crm.service.PpUserService;
import com.lzy.crm.wechat.util.WeixinUtil;

/**
 * 游戏登录服务器
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/zy")
public class ZhongYouUserController {

	Logger logger = Logger.getLogger(ZhongYouUserController.class);

	@Resource
	private PpUserService pUserService;

	@Resource
	private CreateRoomInfoService createRoomInfoService;

	@Resource
	private PpSystemStatusInfoService pSystemStatusInfoService;

	@RequestMapping(path = "/login", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String loginGame(HttpServletRequest request, ModelMap model) {
		String code = request.getParameter("code");
		JsonObject json = new JsonObject();

		if (StringUtil.isEmpty(code)) {
			json.addProperty("err", "code is null");
			return json.toString();
		}

		// 用户信息为空 创建用户信息
		String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx7c9f2d1d9066c12b&secret=633366222232afce667df2676b3110bd&grant_type=authorization_code&code="
				+ code;

		JsonObject getCodeResultJson = WeixinUtil.HttpRequest(requestUrl,
				"GET", null);

		logger.info(getCodeResultJson);

		if (getCodeResultJson.has("errcode")) {
			json.addProperty("errcode", getCodeResultJson.get("errcode")
					.getAsString());
			return json.toString();

		}

		String openid = getCodeResultJson.get("openid").getAsString();// 拿到openid
		String unionid = getCodeResultJson.get("unionid").getAsString();// 拿到unionid
		String access_token = getCodeResultJson.get("access_token")
				.getAsString();

		PpUser user = pUserService.getPpUserByUnionId(unionid);

		if (user == null) {
			// 补全信息 或生成信息
			String unioinidrequestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN"
					.replace("OPENID", openid).replace("ACCESS_TOKEN",
							access_token);
			JsonObject userinfoJson = WeixinUtil.HttpRequest(unioinidrequestUrl, "GET", null);
			System.out.println("userinfoJson" + userinfoJson);
			
			if (userinfoJson.has("errcode")) {
				json.addProperty("errcode", getCodeResultJson.get("errcode").getAsString());
				return json.toString();
			}
			
			String nickname = userinfoJson.get("nickname").getAsString();
			String headimgurl = userinfoJson.get("headimgurl").getAsString();
			String sex = userinfoJson.get("sex").getAsString();
			String province = userinfoJson.get("province").getAsString();
			String city = userinfoJson.get("city").getAsString();

			user = new PpUser();
			user.setUphone(null); // `uphone` ' '
			user.setWechat(null); // `wechat` ' '
			user.setRealname(null); // `realname`
			user.setIdnum(null); // `idnum` '暂缺'
			user.setPwd("e10adc3949ba59abbe56e057f20f883e"); // `pwd`
			user.setHeadImgUrl(headimgurl); // `head_img_url` NOT
			user.setAddress(province + city); // `address`
			user.setRid(5); // `rid` '5'
			user.setFrontUid(null); // `front_uid`
			user.setChiefUid(null); // `chief_uid`
			user.setNickname(nickname); // `nickname`
			user.setRoomcard(5); // `roomcard`
			user.setBubble(0); // `bubble` '0'
			user.setRechargeUid(null); // `recharge_uid` NOT
			user.setFreeze(2); // `freeze`
			user.setCreateTime(new Date()); // `create_time`
			user.setUpperLimit(null); // `upper_limit`
			user.setLowerLimit(null); // `lower_limit`
			user.setSex(Integer.parseInt(sex)); // `sex` NOT
			user.setAccessTime(new Date()); // `access_time`
			user.setUnionid(unionid); // `unionid` ''
			user.setOpenid(openid); // `openid` ''
			user.setToken(access_token); // `token` ''
			user.setRefreshToken(access_token); // `refresh_token`
			user.setMoney(0); // `money` '0'
			user.setUstate(0); // `ustate` '0'
			user.setFlag(0); // `flag` '0'
			user.setBackgold(0.0); // `backgold`
			user.setBackcard(0); // `backcard`
			user.setRoomId(0); // `room_id` '0',
			user.setCode(0); // `code` '0' '推广码',
			user.setUserLevel(9); // `user_level` '9'

			pUserService.insertSelective(user);
			
			// 更新Redis

			Map<String, String> map = new HashMap<String, String>();
			map.put("unionid", user.getUnionid());
			map.put("openid", user.getOpenid());
			map.put("headimgurl", user.getHeadImgUrl());
			map.put("access_token", user.getToken());
			map.put("name", user.getNickname());
			map.put("province", user.getAddress());
			map.put("country", user.getAddress());
			map.put("cash_num", user.getRoomcard().toString());
			map.put("city", user.getAddress());
			map.put("sex", user.getSex().toString());
			map.put("refresh_token", user.getRefreshToken());
			
			System.out.println("account:" + user.getUid() + ":data====>"+map.toString());
			
			RedisHelper.hmset("account:" + user.getUid() + ":data", map);
			
		} else {
			user.setAccessTime(new Date());
			pUserService.updateByPrimaryKeySelective(user);
		}

		

		json.addProperty("pid", user.getUid());
		json.addProperty("key", user.getAccessTime().toString());

		return json.toString();
	}

	@RequestMapping(path = "/guest_login", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String Guestlogin(HttpServletRequest request, ModelMap model) {
		String code = request.getParameter("code");
		JsonObject json = new JsonObject();

		if (StringUtil.isEmpty(code)) {
			json.addProperty("err", "code is null");
			return json.toString();
		}

		PpUser user = pUserService.getPpUserByUnionId(code);

		if (user == null) {
			user = new PpUser();
			user.setUphone(code);
			user.setWechat(code);
			user.setRealname(code);
			user.setIdnum(code);
			user.setPwd(code);
			user.setHeadImgUrl("http://thirdwx.qlogo.cn/mmopen/vi_32/oA8yhGYuVMBurqC5ZI1MLhM4bg4LuVJbWicUGe24zXmXDdPiacFdR7yulKKf9n6NeswC326Oz4iaw6xw37PzhibFicQ/132");
			user.setAddress(code);
			user.setRid(5);
			user.setFrontUid(null);
			user.setChiefUid(null);
			user.setNickname(code);
			user.setRoomcard(5);
			user.setBubble(0);
			user.setRechargeUid(null);
			user.setFreeze(2);
			user.setCreateTime(new Date());
			user.setUpperLimit(null);
			user.setLowerLimit(null);
			user.setSex(0);
			user.setAccessTime(new Date());
			user.setUnionid(code);
			user.setOpenid(code);
			user.setToken(code);
			user.setRefreshToken(code);
			user.setMoney(0);
			user.setUstate(0);
			user.setFlag(0);
			user.setBackgold(0.0);
			user.setBackcard(0);
			user.setRoomId(0);
			user.setCode(0);
			user.setUserLevel(9);
			
			pUserService.insertSelective(user);
			
			// 更新Redis

			Map<String, String> map = new HashMap<String, String>();
			map.put("unionid", user.getUnionid());
			map.put("openid", user.getOpenid());
			map.put("headimgurl", user.getHeadImgUrl());
			map.put("access_token", user.getToken());
			map.put("name", user.getNickname());
			map.put("province", user.getAddress());
			map.put("country", user.getAddress());
			map.put("cash_num", user.getRoomcard().toString());
			map.put("city", user.getAddress());
			map.put("sex", user.getSex().toString());
			map.put("refresh_token", user.getRefreshToken());

			System.out.println("account:" + user.getUid() + ":data====>"+map.toString());
			
			RedisHelper.hmset("account:" + user.getUid() + ":data", map);

		}

	
		json.addProperty("pid", user.getUid());
		json.addProperty("key", user.getAccessTime().toString());

		return json.toString();
	}

	@RequestMapping(path = "/login_xianliao", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String loginXianLiao(HttpServletRequest request, ModelMap model) {
		String code = request.getParameter("code");
		JsonObject json = new JsonObject();

		if (StringUtil.isEmpty(code)) {
			json.addProperty("err", "code is null");
			return json.toString();
		}

		// 用户信息为空 创建用户信息
		String data = "appid=y63pchhFaGAvH9yC&appsecret=i3sJjhmRmlEzsdC7&grant_type=authorization_code&code="
				+ code;
		JsonObject tokenJson = WeixinUtil.HttpRequest(
				"https://ssgw.updrips.com/oauth2/accessToken", "POST", data);

		logger.info("tokenJson = " + tokenJson);

		if (tokenJson.has("err_code")
				&& !tokenJson.get("err_code").getAsString().equals("0")) {
			json.addProperty("err", tokenJson.get("err_code").getAsString());
			return json.toString();
		}

		JsonObject tokens = tokenJson.getAsJsonObject("data");

		String refresh_token = tokens.get("refresh_token").getAsString();
		String access_token = tokens.get("access_token").getAsString();

		JsonObject userinfoJson = WeixinUtil.HttpRequest(
				"https://ssgw.updrips.com/resource/user/getUserInfo", "POST",
				"access_token=" + access_token);

		logger.info("xianliao-userinfoJson" + userinfoJson);

		if (userinfoJson.has("err_code")
				&& !tokenJson.get("err_code").getAsString().equals("0")) {
			json.addProperty("err", userinfoJson.get("err_code").getAsString());
			return json.toString();
		}

		JsonObject info = userinfoJson.getAsJsonObject("data");

		String openId = info.get("openId").getAsString();
		String nickname = info.get("nickName").getAsString();
		String headimgurl = info.get("originalAvatar").getAsString();
		int gender = info.get("gender").getAsInt();

		PpUser user = pUserService.getPpUserByUnionId(openId);

		if (user == null) {

			user = new PpUser();
			user.setUphone(null); // `uphone` ' '
			user.setWechat(null); // `wechat` ' '
			user.setRealname(null); // `realname`
			user.setIdnum(null); // `idnum` '暂缺'
			user.setPwd("e10adc3949ba59abbe56e057f20f883e"); // `pwd`
			user.setHeadImgUrl(headimgurl); // `head_img_url` NOT
			user.setRid(5); // `rid` '5'
			user.setFrontUid(null); // `front_uid`
			user.setChiefUid(null); // `chief_uid`
			user.setNickname(nickname); // `nickname`
			user.setRoomcard(5); // `roomcard`
			user.setBubble(0); // `bubble` '0'
			user.setRechargeUid(null); // `recharge_uid` NOT
			user.setFreeze(2); // `freeze`
			user.setCreateTime(new Date()); // `create_time`
			user.setUpperLimit(null); // `upper_limit`
			user.setLowerLimit(null); // `lower_limit`
			user.setSex(gender); // `sex` NOT
			user.setAccessTime(new Date()); // `access_time`
			user.setUnionid(openId); // `unionid` ''
			user.setOpenid(openId); // `openid` ''
			user.setToken(access_token); // `token` ''
			user.setRefreshToken(refresh_token); // `refresh_token`
			user.setMoney(0); // `money` '0'
			user.setUstate(0); // `ustate` '0'
			user.setFlag(0); // `flag` '0'
			user.setBackgold(0.0); // `backgold`
			user.setBackcard(0); // `backcard`
			user.setRoomId(0); // `room_id` '0',
			user.setCode(0); // `code` '0' '推广码',
			user.setUserLevel(9); // `user_level` '9'

			Integer newUid = pUserService.insertSelective(user);
			
			// 更新Redis

			Map<String, String> map = new HashMap<String, String>();
			map.put("unionid", user.getUnionid());
			map.put("openid", user.getOpenid());
			map.put("headimgurl", user.getHeadImgUrl());
			map.put("access_token", user.getToken());
			map.put("name", user.getNickname());
			map.put("cash_num", user.getRoomcard().toString());
			map.put("sex", user.getSex().toString());
			map.put("refresh_token", user.getRefreshToken());

			RedisHelper.hmset("account:" + user.getUid() + ":data", map);

		} else {
			user.setAccessTime(new Date());
			pUserService.updateByPrimaryKeySelective(user);
		}

		

		json.addProperty("pid", user.getUid());
		json.addProperty("key", user.getAccessTime().toString());

		return json.toString();
	}
}
